package com.briup.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.briup.cms.dao.ArticleDao;
import com.briup.cms.dao.UserDao;
import com.briup.cms.domain.Article;
import com.briup.cms.domain.Comment;
import com.briup.cms.dao.CommentDao;
import com.briup.cms.domain.User;
import com.briup.cms.domain.param.CommentQueryParam;
import com.briup.cms.exception.ServiceException;
import com.briup.cms.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.briup.cms.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author briup
 * @since 2023-03-09
 */
@Service
public class CommentServiceImpl implements ICommentService {

    @Autowired
    UserDao userDao;
    @Autowired
    ArticleDao articleDao;
    @Autowired
    CommentDao commentDao;

    @Override
    public void addComment(Comment comment) {
        if(comment == null)
            throw new ServiceException(ResultCode.PARAM_IS_BLANK);
        if(comment.getUserId()==null || comment.getArticleId()==null)
            throw new ServiceException(ResultCode.PARAM_NOT_COMPLETE);

        User user = userDao.selectById(comment.getUserId());
        if(user == null)
            throw new ServiceException(ResultCode.DATA_NONE);

        Article article = articleDao.selectById(comment.getArticleId());
        if(article == null)
            throw new ServiceException(ResultCode.DATA_NONE);
        comment.setPublishTime(LocalDateTime.now());
        commentDao.insert(comment);

    }

    @Override
    public void deleteById(Long id) {
        commentDao.deleteById(id);
    }

    @Override
    public List<Comment> queryByArticleId(Long articleId) {
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Comment::getArticleId,articleId);
        wrapper.orderByDesc(Comment::getPublishTime);
        List<Comment> comments = commentDao.selectList(wrapper);
        return comments;
    }

    @Override
    public IPage<Comment> query(CommentQueryParam param) {
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(param.getUserId()!=null,Comment::getUserId,param.getUserId());
        wrapper.eq(param.getArticleId()!=null,Comment::getArticleId,param.getArticleId());
        wrapper.like(param.getContent()!=null,Comment::getContent,param.getContent());
        wrapper.between(Comment::getPublishTime,param.getStartTime(),param.getEndTime());
        Page<Comment> page = new Page<>(param.getPageNum(), param.getPageSize());
        commentDao.selectPage(page,wrapper);
        return page;
    }
}
